package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.BiConsumer;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 指定区间营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        //当前集合存放begin-end的日期
        List<LocalDate> list = new ArrayList();
        list.add(begin);

        while (!begin.equals(end)) {
            //如果begin!=end 天数+1
            begin = begin.plusDays(1);
            list.add(begin);
        }

        List<Double> amountList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //获取一天中的最大和最小时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //获取该日的总收益
            Double amount = ordersMapper.getAmountBydata(beginTime, endTime, Orders.COMPLETED);
            //如果该日没有收益，则查出来的数据为null，需要转换成0.0
            amount = amount == null ? amount = 0.0 : amount;
            amountList.add(amount);
        }

        //将日期,总收益拼接成字符串
        String dateStr = StringUtils.join(list, ",");
        String amountStr = StringUtils.join(amountList, ",");
        //封装进vo对象
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(dateStr)
                .turnoverList(amountStr)
                .build();

        return reportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserReport(LocalDate begin, LocalDate end) {
        //存放当前begin-end的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //新增用户数量集合
        List<Integer> newUserList = new ArrayList<>();
        //总用户数量集合
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //分别获取新增用户数量 和 总用户数量
            int newUser = userMapper.getUserBydate(beginTime, endTime);
            int totalUser = userMapper.getUserBydate(null, endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        //将日期时间，新增用户数量，总用户数量集合，转换成字符串，用逗号隔开
        String dateStr = StringUtils.join(dateList, ",");
        String newUserStr = StringUtils.join(newUserList, ",");
        String totalUserStr = StringUtils.join(totalUserList, ",");

        UserReportVO userReport = UserReportVO.builder()
                .dateList(dateStr)
                .newUserList(newUserStr)
                .totalUserList(totalUserStr)
                .build();
        return userReport;
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //存放日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            //如果开始时间！=结束时间，那么开始时间+1
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每天的订单数量
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数量
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //每天的订单数量
            Integer everyDayOrderCount = ordersMapper.getOrderCount(beginTime, endTime, null);
            orderCountList.add(everyDayOrderCount);
            //每天有效订单数量
            Integer everyDayValidOrderCount = ordersMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(everyDayValidOrderCount);

        }
        //总订单数量
        Integer allOrderCount = ordersMapper.getOrderCount(null, null, null);
        //有效订单总数量
        Integer validOrderCount = ordersMapper.getOrderCount(null, null, Orders.COMPLETED);

        Double orderCompletion = 0.0;
        if (allOrderCount != 0) {
            //订单完成率
            orderCompletion = validOrderCount.doubleValue() / allOrderCount;
        }


        //将日期，每天订单数和每天有效订单数转换成字符串
        String dateStr = StringUtils.join(dateList, ",");
        String orderCountStr = StringUtils.join(orderCountList, ",");
        String validOrderCountStr = StringUtils.join(validOrderCountList, ",");

        //封装进vo对象
        OrderReportVO orderReport = OrderReportVO.builder()
                .dateList(dateStr)
                .orderCountList(orderCountStr)
                .validOrderCountList(validOrderCountStr)
                .totalOrderCount(allOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletion)
                .build();

        return orderReport;
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        //商品集合
        List<String> nameList = new ArrayList<>();
        //销量集合
        List<Integer> numberList = new ArrayList<>();

        //转换时间对象
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //获取当前日期中所有订单u
        List<GoodsSalesDTO> GoodsSales = ordersMapper.getOrderBydate(beginTime, endTime);

        for (GoodsSalesDTO goodsSale : GoodsSales) {
            nameList.add(goodsSale.getName());
            numberList.add(goodsSale.getNumber());
        }

        //将集合拼接成字符串
        String nameStr = StringUtils.join(nameList, ",");
        String numberStr = StringUtils.join(numberList, ",");
        //封装进vo对象
        SalesTop10ReportVO salesTop10Report = SalesTop10ReportVO.builder()
                .nameList(nameStr)
                .numberList(numberStr)
                .build();
        return salesTop10Report;

    }

    /**
     * 数据导出
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {
        //近三十天的日期
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MIN));

        //通过poi将数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(in);

//        填充数据
        XSSFSheet sheet = excel.getSheet("sheet1");
        sheet.getRow(1).getCell(1).setCellValue("时间："+beginTime+"——"+endTime);

        //获取第四行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());

        //获取第五行
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());


        //填充明细数据
        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate dateTime = LocalDate.now().minusDays(30);
            dateTime = dateTime.plusDays(i);
            BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(dateTime, LocalTime.MIN),
                                                                            LocalDateTime.of(dateTime, LocalTime.MAX));
            //从第八行开始获取行
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(dateTime.toString());
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
        }

        //通过输出流将excel文件下载到客户端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();

    }
}
